package com.client;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.gateway.core.MyBuffer;
import com.gateway.core.MyProtocol;
import com.gateway.entity.LogicServer;

public class ClientHandler extends IoHandlerAdapter {

  private static final String CONNECTION_LOGIC_SERVER="connectionLogicServer";

  private Logger log=Logger.getLogger(this.getClass());

  public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception {
  }

  public void messageReceived(IoSession session, Object obj) throws Exception {
    MyProtocol myProtocol=(MyProtocol)obj;
    MyBuffer buf=new MyBuffer(myProtocol.getBodyData());
    String name=buf.getString();
    if(buf.remaining() > 0) {
      String ip=buf.getString();
      int port=buf.getInt();
      log.debug(name + "," + ip + "," + port);
      LogicServer ls=new LogicServer();
      ls.setName(name);
      ls.setIp(ip);
      ls.setPort(port);
      session.setAttribute(CONNECTION_LOGIC_SERVER, ls);
      session.close(true);
    } else {
      log.debug(name);
    }
  }

  public void messageSent(IoSession arg0, Object arg1) throws Exception {
  }

  public void sessionClosed(IoSession session) throws Exception {
    log.debug("disconnected with the Gateway!");
    LogicServer ls=(LogicServer)session.getAttribute(CONNECTION_LOGIC_SERVER);
    if(ls != null) {
      log.debug("ready to connection LOGIC_SERVER:" + ls);
      new Client().connectionLogicServer(ls);
    } else {
      log.debug("not need to connection LOGIC_SERVER");
    }
  }

  public void sessionCreated(IoSession session) throws Exception {
  }

  public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
  }

  public void sessionOpened(IoSession arg0) throws Exception {
  }
}
